package com.app.micaihu.utils;

import android.app.Activity;
import android.content.DialogInterface;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.bean.DataBean;

import com.app.micaihu.bean.infor.UserInfor;
import com.app.micaihu.bean.speak.ICommentEntity;
import com.app.micaihu.bean.comment.NormalComment;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.components.ParamMap;
import com.app.micaihu.custom.view.dataview.MyExpressView;

import com.app.micaihu.custom.view.dialog.DismisiDialog;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.view.comment.SubmitCommentListener;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.ViewFrameUtils;
import com.app.utils.util.ViewSizeUtils;
import com.app.utils.util.view.expression.view.BiaoQinEditView;
import com.blankj.utilcode.util.ActivityUtils;
import com.google.gson.reflect.TypeToken;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Guo on 2016/12/19.
 * <p>
 * <p>
 * 评论的工具类
 */

public class CommentUtils1 implements TextWatcher, View.OnClickListener, DialogUtils.OnDialogBtnClickListener, DismisiDialog.OnDismissListener {
    private DismisiDialog dialog;// 评论dialog
    private BiaoQinEditView commentEdit;// 评论编辑框
    private TextView commentSend;// 发表评论按钮

    private MyExpressView biaoqingView;//表情控件

    private String commentMsg;// edittext显示的默认字
    private ICommentEntity currentReplyComment;// 当前的被回复评论
    private Activity mActivity;


    private static CommentUtils1 mCommontUtils;
    private static Map<String, String> mCacheComStr;//缓存的评论内容
    private SubmitCommentListener mSubmitCommentListener;//评论监听
    private String newsId;//文章id
    private String mRrequestName;//网络请求标识
    private boolean isSaveComStr = true;//是否存储评论(评论成功就不存了)
    private String mCacheKey;//评论存储唯一键
    private static long mOldCommentTime;//上次评论的时间
    private static String mOldNewsid;//上一次发表的文章的id
    private static String mOldNewsComment;//上一次发表的文章的评论
    private boolean isComment;
    private boolean isSecondary;


    /**
     * 获取唯一实例
     *
     * @return CommentUtils
     */
    public static CommentUtils1 getInstance() {
        if (mCommontUtils == null) {
            mCommontUtils = new CommentUtils1();
        }
        return mCommontUtils;
    }

    private CommentUtils1() {
        mCacheComStr = new HashMap<String, String>();
    }


    public void showDialogInSecondaryPost(Activity activity, String requestName, String newsId, ICommentEntity iComment,
                                          SubmitCommentListener mSubmitCommentListener, boolean isComment, boolean isSecondary) {
        this.isSecondary = isSecondary;
        showDialog(activity, requestName, newsId, iComment, mSubmitCommentListener, isComment, false);
    }


    /**
     * 展示评论弹窗
     *
     * @param activity
     * @param newsId   保存评论的唯一建
     */
    public void showDialog(Activity activity, String requestName, String newsId, ICommentEntity iComment,
                           SubmitCommentListener mSubmitCommentListener, boolean isComment, boolean isQuestion) {

        this.isComment = isComment;
        if (this.mActivity == activity) {
            //同一界面弹窗,则不用再初始化界面
            if (dialog == null) {
                initDialog();
            }
        } else {
            //如果不是同一界面则重新初始化dialgo
            this.mActivity = activity;
            initDialog();
        }
        if (dialog == null) {
            return;
        }
        //获取之前保存的评论
        if (mCacheComStr == null) {
            mCacheComStr = new HashMap<String, String>();
        }
        String showStr;
        if (iComment != null) {
            mCacheKey = iComment.getICommentId();
            if (isQuestion) {
                commentEdit.setHint(AppApplication.getInstance().getString(R.string.speak_dialog_replay_hint, iComment.getINickName()));
            } else {
                commentEdit.setHint(AppApplication.getInstance().getString(R.string.speak_dialog_replayhint, iComment.getINickName()));
            }

        } else {
            mCacheKey = newsId;
            commentEdit.setHint(AppApplication.getInstance().getString(R.string.speak_dialog_hint));
        }
        showStr = mCacheComStr.get(mCacheKey);
        //如果为空就不用适配表情了
        if (TextUtils.isEmpty(showStr)) {
            commentEdit.setText(showStr);
        } else {
            commentEdit.setPicText(showStr);
        }
        commentEdit.setSelection(commentEdit.getText().length());
        //展示dialog
        if (mActivity != null && !mActivity.isFinishing() && dialog.getWindow() != null) {
            try {
                dialog.show();
                dialog.getWindow().setLayout(ViewSizeUtils.getWidthPixels(),
                        android.view.WindowManager.LayoutParams.WRAP_CONTENT);
            } catch (Exception e) {
                e.printStackTrace();
            }
            ViewFrameUtils.showSoftwareByView(commentEdit);
            //设置当前评论的数据
            this.currentReplyComment = iComment;
            this.mSubmitCommentListener = mSubmitCommentListener;
            this.newsId = newsId;
            this.mRrequestName = requestName;
        }
    }

    /**
     * 初始化dialog
     */
    private void initDialog() {
        if (mActivity == null) return;
        dialog = new DismisiDialog(mActivity, R.style.CustomDialogStyle);
        View commentDialogView = mActivity.getLayoutInflater().inflate(
                R.layout.dialog_comment_edit, null);
        commentEdit = (BiaoQinEditView) commentDialogView
                .findViewById(R.id.et_comment_msg);
        commentSend = (TextView) commentDialogView
                .findViewById(R.id.tv_comment_send);
        View expressionView = commentDialogView.findViewById(R.id.iv_expression);
        expressionView.setOnClickListener(this);
        commentEdit.addTextChangedListener(this);
        commentSend.setOnClickListener(this);
        //配置表情
        View bottomView = commentDialogView.findViewById(R.id.rl_comment_bottom);
        biaoqingView = (MyExpressView) commentDialogView.findViewById(R.id.comment_biaoqing);
        //配置表情显示的控件
        biaoqingView.configView(commentEdit, bottomView, 5, R.drawable.expression_yuandian, mActivity);
        //暂时隐藏表情按钮
        biaoqingView.setVisibility(View.GONE);
        commentEdit.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    //隐藏表情
                    if (biaoqingView.getVisibility() == View.VISIBLE) {
                        biaoqingView.setVisibility(View.GONE);
                    }
                }
                return false;
            }
        });

        dialog.setCanceledOnTouchOutside(true);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                //如果当前允许存储则 存储当前的评论
                setSaveComStrKey();
                if (biaoqingView != null && biaoqingView.getVisibility() == View.VISIBLE) {
                    biaoqingView.setVisibility(View.GONE);
                }
            }
        });
        if (dialog.getWindow() == null) {
            return;
        }
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.getWindow().setContentView(commentDialogView);
        dialog.setOnDismissListener(CommentUtils1.this);
    }


    /**
     * 隐藏dialog
     */
    public void hideDialog() {
        //关闭键盘
        ViewFrameUtils.closeInputSoft(mActivity, commentEdit);
        if (this.dialog != null) {
            try {
                this.dialog.hide();
            } catch (Exception e) {
            }
        }
        setSaveComStrKey();
    }

    /**
     * 存储评论键
     */
    private void setSaveComStrKey() {
        //如果当前允许存储则 存储当前的评论
        if (mCacheComStr == null) {
            mCacheComStr = new HashMap<String, String>();
        }
        if (isSaveComStr) {
            mCacheComStr.put(mCacheKey, commentMsg);
        }
    }

    /**
     * 退出dialog
     */
    public void dismissDialog() {
        if (this.dialog != null) {
            try {
                this.dialog.dismiss();
                this.dialog = null;

            } catch (Exception e) {
            }
        }
    }

    /**
     * 得到评论内容控件
     *
     * @return
     */
    public EditText getCommentEditView() {
        return commentEdit;
    }


    /**
     * 发表稿子评论（包括稿子评论和稿子评论的回复）
     */
    private void sendComment() {
        if (this.mActivity == null) {
            return;
        }
        if (TextUtils.isEmpty(commentMsg)) {
            ToastUtils.showText(AppApplication.getInstance().getString(R.string.speak_erro_empty));
            return;
        } else if (!UserInforManager.getInstance().isLogin()) {
            //判断是否登陆
            UserInforManager.getInstance().toLoginPage(this.mActivity);
            return;
        } else if (TextUtils.isEmpty(newsId)) {
            ToastUtils.showText(AppApplication.getInstance().getString(R.string.speak_erro_fail));
            return;
        } else if (TextUtils.equals(mOldNewsid, newsId)
                && TextUtils.equals(commentMsg, mOldNewsComment)
                && !compareTime()) {
            //如果一分钟内对同一篇文章连续发表同样的评论则不允许发表
            ToastUtils.showText(AppApplication.getInstance().getString(R.string.speak_erro_same));
            return;
        }

        UserInfor userinfo = UserInforManager.getInstance().getUserInfor();
        ParamMap paramMap = new ParamMap();

        if (isComment) {
            paramMap.putEncode("articleId", newsId);
        } else {
            paramMap.putEncode("topicId", newsId);
            paramMap.putEncode("files", "");
            paramMap.putEncode("title", "");//title
        }


        paramMap.putEncode("uid", userinfo.getUid());
        paramMap.putEncode("content", commentMsg);

        if (this.currentReplyComment != null) {
            paramMap.putEncode("commentId", this.currentReplyComment.getICommentId());
            paramMap.putEncode("toUid", this.currentReplyComment.getIToUid());

            //TODO
            if (isComment) {
                if (TextUtils.equals(currentReplyComment.getIType(), TypeConstant.COMMENT_ONE)
                        || TextUtils.equals(currentReplyComment.getIType(), TypeConstant.COMMENT_TWO)) {
                    paramMap.putEncode("type", TypeConstant.COMMENT_TWO);//2 评论的评论
                } else {
                    paramMap.putEncode("type", TypeConstant.COMMENT_ONE);//1 一级子评论
                }
            } else {

                if (TextUtils.equals(currentReplyComment.getIType(), TypeConstant.COMMENT_TWO)) {
                    paramMap.putEncode("type", TypeConstant.COMMENT_TWO);//2 评论的评论

                } else if (TextUtils.equals(currentReplyComment.getIType(), TypeConstant.COMMENT_ONE)) {
                    if (TextUtils.equals(ActivityUtils.getTopActivity().getLocalClassName(), "view.comment.SecondaryCommentDetailActivity")) {
                        if (isSecondary) {
                            paramMap.putEncode("type", TypeConstant.COMMENT_ONE);//1 一级子评论
                        } else {
                            paramMap.putEncode("type", TypeConstant.COMMENT_TWO);//2 评论的评论

                        }


                    } else {
                        paramMap.putEncode("type", TypeConstant.COMMENT_ONE);//1 一级子评论
                    }
                } else {
                    paramMap.putEncode("type", TypeConstant.COMMENT_ONE);//1 一级子评论
                }
            }


        } else {
//            if(isComment){
            paramMap.putEncode("commentId", "");
            paramMap.putEncode("toUid", "");
            paramMap.putEncode("type", TypeConstant.COMMENT_PARENT);//0为资讯
//            }else{
//
//            }


        }

        HttpUtils.ParmsMapMD5(paramMap);

        HttpListener<DataBean<NormalComment>> httpListener = new HttpListener<DataBean<NormalComment>>() {

            @Override
            public void onStart() {
                isSaveComStr = true;
                DialogUtils.getInstance().showProgressDialog(mActivity, AppApplication.getInstance().getString(R.string.speak_submiting));
                mOldCommentTime = System.currentTimeMillis();//获取当前的发表时间
                if (mSubmitCommentListener != null) {
                    mSubmitCommentListener.startSubmit();
                }
            }

            @Override
            public void onError(VolleyError error) {
                DialogUtils.getInstance().dismissProgressDialog();
                ToastUtils.showText(AppApplication.getInstance().getString(R.string.neterror));
                if (mSubmitCommentListener != null) {
                    mSubmitCommentListener.errorSubmit(error);
                }
            }

            @Override
            public void onSuccess(DataBean<NormalComment> response) {
                DialogUtils.getInstance().dismissProgressDialog();
                if (response.noError()) {
                    setCommentResult(response.getData(), mSubmitCommentListener);
                } else {
                    ToastUtils.makeText(response.getMsg());
                }
            }
        };

        //请求网络
        //帖子的回复

        if (isComment) {
            HttpUtils.addPostRequest(URIContant.NEWS_SENDCOMMENT, new TypeToken<DataBean<NormalComment>>() {
            }.getType(), mRrequestName, paramMap, httpListener);
        } else {
            HttpUtils.addPostRequest(URIContant.TOPIC_POST_LEAVEMSG_2052, new TypeToken<DataBean<NormalComment>>() {
            }.getType(), mRrequestName, paramMap, httpListener);
        }


    }

    /**
     * 设置评论结果
     *
     * @param resultComment
     * @param listener
     */
    private void setCommentResult(NormalComment resultComment, SubmitCommentListener listener) {
        if (resultComment == null) {
            ToastUtils.makeText(R.drawable.handle_fail, AppApplication.getInstance().getString(R.string.speak_error));
            return;
        }
        isSaveComStr = false;//改变配置不存储评论
        mOldNewsid = newsId;//重置上次发表的文章id
        mOldNewsComment = resultComment.getContent();//重置发表的内容
        ToastUtils.makeText(R.drawable.handle_success, AppApplication.getInstance().getString(R.string.speak_sucess));
        hideDialog();//隐藏dialog
        dismissDialog();
        if (listener != null) {
            listener.successSubmit(resultComment);
        }
        if (resultComment.getIsGetTask(AppApplication.getInstance().getString(R.string.speak_sucess_taost))) {
            UserInforManager.getInstance().getUserTask(mActivity, false);//刷新用户任务
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
                                  int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

        isSaveComStr = true;
        commentMsg = commentEdit.getText().toString();
        if ("".equals(commentMsg)) {
            commentSend.setEnabled(false);
        } else {
            commentSend.setEnabled(true);
        }
    }

    /**
     * 布局中的点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        if (v == null) return;
        switch (v.getId()) {
            case R.id.tv_comment_send://发表评论
                StatServiceUtils.event(Config.EventBauduId.teamdetail_inputsucces, "军团详情_输入框发布");
                sendComment();
                break;
            case R.id.iv_expression://展示表情
                StatServiceUtils.event(Config.EventBauduId.teamdetail_face, "军团详情_评论框表情");
                showBiaoqing();
                break;

            case R.id.btn_negative://展示出来的dialog的取消键
                DialogUtils.getInstance().dismissCDialog();
                break;
            case R.id.btn_positive://展示出来的dialog的确定键
                DialogUtils.getInstance().dismissCDialog();
                deleteComment(currentReplyComment.getNewsId(), currentReplyComment.getICommentId()
                        , currentReplyComment.getIType(), this.mSubmitCommentListener, "");
                break;
        }
    }

    /**
     * 比较上次发表的时间看是否允许发送
     *
     * @return
     */
    private boolean compareTime() {
        long currentTime = System.currentTimeMillis();
        //如果两次发表的间隔小于60秒
        if ((currentTime - mOldCommentTime) / 1000 < 60) {
            return false;
        }
        return true;
    }


    /**
     * 展示表情
     */
    private void showBiaoqing() {
        if (biaoqingView == null) {
            return;
        }
        //展示或隐藏表情
        biaoqingView.showOrHideView();
    }


    /**
     * 删除评论的方法
     *
     * @param articlId    文章Id
     * @param commentId   评论Id
     * @param commentType 几级评论类型
     */
    public void deleteComment(String articlId, String commentId, String commentType, final SubmitCommentListener mSubmitCommentListener, String packageName) {
        if (UserInforManager.getInstance().isLogin()) {
            ParamMap paramMap = new ParamMap();
            paramMap.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());
            paramMap.putEncode("articleId", articlId);
            paramMap.putEncode("commentId", commentId);
            paramMap.putEncode("type", commentType);
            HttpUtils.ParmsMapMD5(paramMap);

            HttpListener<DataBean> deleteListener = new HttpListener<DataBean>() {
                @Override
                public void onStart() {
                    super.onStart();
                    if (mSubmitCommentListener != null) {
                        mSubmitCommentListener.startSubmit();
                    }
                }

                @Override
                public void onError(VolleyError error) {
                    if (mSubmitCommentListener != null) {
                        mSubmitCommentListener.errorSubmit(error);
                    }
                }

                @Override
                public void onSuccess(DataBean response) {
                    if (TextUtils.equals(response.getCode(), "0")) {

                        if (mSubmitCommentListener != null) {
                            mSubmitCommentListener.successSubmit(null);
                        }
                    } else {
                        if (mSubmitCommentListener != null) {
                            mSubmitCommentListener.errorSubmit(null);
                        }
                    }
                }
            };
            HttpUtils.addPostRequest(URIContant.DELETE_COMMENT, new TypeToken<DataBean>() {
            }.getType(), packageName, paramMap, deleteListener);
        }
    }


    /**
     * 展示 删除dialog 的方法
     * <p>
     * 删除时直接调用这个方法即可，点击事件等已经写好了
     *
     * @param activity
     * @param isPost   是帖子还是评论
     */
    public void showDeleteDialog(Activity activity, ICommentEntity iComment, SubmitCommentListener mSubmitCommentListener, boolean isPost) {
        this.mActivity = activity;
        this.currentReplyComment = iComment;
        this.mSubmitCommentListener = mSubmitCommentListener;

        HashMap<String, String> style = new HashMap<>();
        if (isPost) {
            style.put("title", mActivity.getResources().getString(R.string.post_del_title));
            style.put("desc", mActivity.getResources().getString(R.string.post_del_msg));
        } else {
            style.put("title", mActivity.getResources().getString(R.string.comment_del_title));
            style.put("desc", mActivity.getResources().getString(R.string.comment_del_msg));
        }

        style.put("btnPosi", mActivity.getResources().getString(R.string.common_confirm));
        style.put("btnNega", mActivity.getResources().getString(R.string.common_cancel));

        DialogUtils.getInstance().setOnDialogBtnClick(this);
        DialogUtils.getInstance().showCustomDialog(activity, style);


    }


    @Override
    public void onPositiveClick() {
        DialogUtils.getInstance().dismissCustomDialog();
//        if (TextUtils.isEmpty(currentReplyComment.getIArticleId())){
//            deleteComment(currentReplyComment.getITopicId(),currentReplyComment.getICommentId()
//                    ,currentReplyComment.getIType(),this.mSubmitCommentListener,"");
//        }else{
        deleteComment(currentReplyComment.getNewsId(), currentReplyComment.getICommentId()
                , currentReplyComment.getIType(), this.mSubmitCommentListener, "");
//        }

    }

    @Override
    public void onNegativeClick() {
        DialogUtils.getInstance().dismissCustomDialog();
    }

    @Override
    public void onDismiss() {
        isSecondary = false;

    }
}
